<template>
  <div class="viewContain">
    <el-row>
      <el-col :span="8">
        <el-card shadow="hover" :style="tree" class="tree">
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :props="defaultProps"
            :data="orgTreeDate"
            accordion
            default-expand-all
            highlight-current
            @current-change="CurrentNode"
          />
        </el-card>
      </el-col>
      <el-col v-loading="loading" :offset="4" :span="12">
        <section v-if="!isAdd" class="top-button">
          <el-button size="mini" type="primary" @click="addArea">新增</el-button>
          <el-button size="mini" type="primary" @click="updateArea">修改</el-button>
          <el-button size="mini" type="danger" @click="delArea">删除</el-button>
        </section>
        <section v-if="isAdd" class="top-button">
          <el-button size="mini" type="primary" @click="sureAdd">保存</el-button>
          <el-button size="mini" type="primary" plain @click="closeAdd">取消</el-button>
        </section>
        <section class="tree-right">
          <el-form ref="addLocationForm" :model="addLocationForm" label-width="120px" :rules="addLocationFormRules" size="small">
            <el-col :span="24">
              <el-form-item label="机构编码：" prop="orgCode" style="width: 100%;">
                <el-input v-model="addLocationForm.orgCode" auto-complete="off" placeholder="输入机构编码" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="机构名称：" prop="name" style="width: 100%;">
                <el-input v-model="addLocationForm.name" auto-complete="off" placeholder="输入机构名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="父机构名称：" style="width: 100%;">
                <el-input v-model="addLocationForm.parentOrgName" :disabled="par_disable" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="区域名称：" prop="pro" style="width: 100%;">
                <el-select v-model="addLocationForm.pro" placeholder="请选择" :disabled="pro_disable" style="width: 32%;">
                  <el-option
                    v-for="item in pro_branches"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select v-model="addLocationForm.city" placeholder="请选择" :disabled="city_disable" style="width: 32%;">
                  <el-option
                    v-for="item in city_branches"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select v-model="addLocationForm.village" placeholder="请选择" :disabled="village_disable" style="width: 32%;">
                  <el-option
                    v-for="item in village_branches"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详细地址：" prop="orgAddress" style="width: 100%;">
                <el-input v-model="addLocationForm.orgAddress" auto-complete="off" placeholder="输入详细地址" />
              </el-form-item>
            </el-col>
          </el-form>
        </section>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped>

</style>
<script>
import { getOrgTreeByParentId, getOrgByOrgId, updateOrgByOrgId, insertOrg, delOrgByOrgId } from '@a/core/organization.js'
import { getRegionTreeByParentId, getParentRegionListById } from '@a/core/region.js'
export default {
  data() {
    return {
      loading: false,
      isAdd: false,
      selOne: {},
      pro_branches: [],
      city_branches: [],
      village_branches: [],
      par_disable: true, //  父级是否可填
      pro_disable: true, // 省级是否可选
      city_disable: true, // 市级是否可选
      village_disable: true, // 区级是否可选
      tree: {
        height: window.innerHeight - 200 + 'px'
      },
      treeLoading: false,
      //  区域编码控制是否可读的变量:false是可读，true是不可读
      leafID: '',
      parentOrgName: '',
      parentID: 0,
      //  定义根节点的变量
      paramLeaf: '',
      empty: '',
      // 弹出窗口进行 属性校验
      addLocationFormRules: {
        orgCode: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('机构编码不能为空'))
            } else if (parseInt(value).toString() === 'NaN') {
              return callback(new Error('机构编码只能为数字'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        name: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('机构名称不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        pro: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('区域名称不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        orgAddress: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('详细地址不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      },
      filterText: '',
      checkFlat: '',
      // 新增界面数据 start
      addLocationForm: {
        orgCode: '',
        name: '',
        parentOrgName: '',
        pro: '',
        city: '',
        village: '',
        orgAddress: ''
      },
      // 新增界面数据 end

      orgTreeDate: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      orgId: '',
      oId: ''
    }
  },
  created() {
    this.orgId = JSON.parse(localStorage.getItem('userInfo')).orgId
    this.orgTreeInit(this.orgId)
    this.getRegionList('pro', 0)
  },
  methods: {
    // 查询区域树形结构  开始
    orgTreeInit(id) {
      this.treeLoading = true
      getOrgTreeByParentId(id).then(res => {
        this.treeLoading = false
        if (res.code === 0 && res.data) {
          const { orgId, name, parentOrgId, children } = res.data && res.data[0]
          const oChildren = this.recursionChi(children)
          this.orgTreeDate = [{
            pid: parentOrgId,
            id: orgId,
            label: name,
            children: oChildren
          }]
          this.CurrentNode(this.orgTreeDate[0])
        } else {
          this.$message({
            message: res,
            type: 'error'
          })
        }
      }).catch(err => {
        this.treeLoading = false
        console.log(err)
      })
    },
    // 递归处理children
    recursionChi(chi) {
      if (chi) {
        const chiArr = chi.map(item => {
          const { orgId, name, parentOrgId, children } = item
          let oChi = []
          if (children) oChi = this.recursionChi(children)
          const o = {
            pid: parentOrgId,
            id: orgId,
            label: name,
            children: oChi
          }
          return o
        })
        return chiArr
      } else {
        return []
      }
    },
    // 点击树节点方法 开始
    CurrentNode(value) {
      this.isAdd = false
      const id = value.id
      // 获取界面内容
      id && this.getOrgDetail(id)
      this.oId = id
      if (!value.children) {
        this.treeLoading = true
        getOrgTreeByParentId(id).then(res => {
          this.treeLoading = false
          if (res.data) {
            const newChild = []
            res.data.map(item => {
              const { orgId, name, parentOrgId } = item
              const o = {
                pid: parentOrgId,
                id: orgId,
                label: name
              }
              newChild.push(o)
            })
            this.$set(value, 'children', newChild)
          }
        }).catch(err => {
          this.treeLoading = false
          console.log(err)
        })
      }
    },
    getOrgDetail(id) {
      this.loading = true
      this.pro_disable = true // 省级是否可选
      this.city_disable = true // 市级是否可选
      this.village_disable = true // 区级是否可选
      getOrgByOrgId(id).then(res => {
        this.loading = false
        if (res.data) {
          this.addLocationForm = res.data
          this.selOne = res.data
          // 获取父级区域
          getParentRegionListById(res.data.distinctId).then(innerRes => {
            if (innerRes.data) {
              if (innerRes.data.length >= 1) {
                const { distinctId: proId } = innerRes.data[0]
                this.$set(this.addLocationForm, 'pro', proId)
                this.selOne.pro = proId
                this.getRegionList('city', proId)
              }
              if (innerRes.data.length >= 2) {
                const { distinctId: cityId } = innerRes.data[1]
                this.$set(this.addLocationForm, 'city', cityId)
                this.selOne.city = cityId
                this.getRegionList('village', cityId)
              }
              if (innerRes.data.length >= 3) {
                const { distinctId: villageId } = innerRes.data[2]
                this.$set(this.addLocationForm, 'village', villageId)
                this.selOne.village = villageId
              }
            }
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    // 【修改】方法 - 开始
    updateArea() {
      this.$refs.addLocationForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const para = Object.assign({}, this.addLocationForm)
          // 发送请求
          updateOrgByOrgId(para).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.orgTreeInit(this.orgId)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }
      })
    },
    // 重置界面内容
    resetForm(formName) {
      if (this.$refs[formName] === undefined) {
        return
      }
      this.$refs[formName].resetFields()
    },
    // 点击【新增】弹出新增界面方法
    addArea() {
      if (JSON.stringify(this.selOne) !== '{}') {
        const { name: parentOrgName, orgId: parentOrgId, pro, city, village } = this.addLocationForm
        this.resetForm('addLocationForm')
        this.isAdd = true
        // 判断区域 --> 设置可选与否
        this.pro_disable = !!(pro) // 省级是否可选
        this.city_disable = !!(city && this.pro_disable) // 市级是否可选
        this.village_disable = !!(village && this.city_disable) || !this.city_disable // 区级是否可选
        this.addLocationForm = {
          parentOrgName,
          parentOrgId,
          pro,
          city,
          village
        }
      } else {
        this.$message({
          message: '请先选择父级区域！',
          type: 'warning'
        })
      }
    },
    // 点击【新增】弹出新增界面方法 结束

    //  功能新增 【保存】方法 - 开始
    sureAdd() {
      this.$refs.addLocationForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const { pro, city, village, name, orgAddress, orgCode, parentOrgId } = this.addLocationForm
          let distinctId = ''
          if (pro) distinctId = pro
          if (city) distinctId = city
          if (village) distinctId = village
          const para = {
            distinctId,
            name,
            orgAddress,
            orgCode,
            orgId: orgCode,
            parentOrgId
          }
          // 发送请求
          insertOrg(para).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.isAdd = false
              this.selOne = {}
              this.orgTreeInit(this.orgId)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }
      })
    },
    closeAdd() {
      this.isAdd = false
      // this.addLocationForm = this.selOne
      this.oId && this.getOrgDetail(this.oId)
    },
    // 【删除】方法-开始
    delArea() {
      if (JSON.stringify(this.selOne) !== '{}') {
        this.$confirm('该机构下可能存在子级,确定删除该机构？', '提示', {}).then(() => {
          this.loading = true
          delOrgByOrgId(this.selOne.orgId).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.selOne = {}
              this.orgTreeInit(this.orgId)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }).catch(() => {})
      } else {
        this.$message({
          message: '请选择要删除的区域！',
          type: 'error'
        })
      }
    },
    // 获取省级数据
    getRegionList(type, parentId) {
      getRegionTreeByParentId(parentId).then(res => {
        if (res.data) {
          const branches = []
          res.data.map(item => {
            const { id: value, label } = item
            const temp = {
              label,
              value
            }
            branches.push(temp)
          })
          switch (type) {
            case 'pro':
              this.pro_branches = branches
              break
            case 'city':
              this.city_branches = branches
              break
            case 'village':
              this.village_branches = branches
              break
            default:
              break
          }
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

